#include <Winsock2.h>
#include <cstdio>
#include <iostream>
#include <string>
using namespace std;

#pragma  comment(lib,"ws2_32.lib")

int init_win_socket()
{
	WSADATA wsaData;

	if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
	{
		return -1;
	}

	return 0;
}

#define Server_Port 10286

DWORD WINAPI handle_client(LPVOID lppara)
{
	int *newfd = (int *)lppara;
	while (1)
	{
		char buff[1024];
		memset(buff, 0, 1024);
		int result = recv(*newfd, buff, 1024, 0);
		if (result <= 0)
		{
			break;
		}
		else
		{
			printf("Receive Data %s, Size: %d \n", buff, result);
			int ret = send(*newfd, buff, result, 0);
			if (ret>0)
			{
				printf("Send Data %s, Size: %d \n", buff, ret);
			}
			else
			{
				break;
			}
		}
		Sleep(10);
	}
	closesocket(*newfd);
	return 0;
}

int run()
{
	int listener;
	struct sockaddr_in addr_server;
	int sock_clients[1024]; //max number for accept client connection;

	listener = socket(AF_INET, SOCK_STREAM, 0);

	//addr_server.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
	addr_server.sin_addr.S_un.S_addr = ADDR_ANY;
	addr_server.sin_family = AF_INET;
	addr_server.sin_port = htons(Server_Port);

	if (bind(listener, (const sockaddr *)&addr_server, sizeof(addr_server)) < 0)
	{
		perror("bind error");
		return -1;
	}

	if (listen(listener, 10)<0)
	{
		perror("listen error");
		return -1;
	}

	printf("Server is listening ... \n");

	int fd_count = 0;
	bool runing = true;
	while (runing)
	{
		sockaddr_in addr_client;
		int clientlen = sizeof(addr_client);
		int client_sock;
		if ((client_sock = accept(listener, (struct sockaddr *) &addr_client, &clientlen)) < 0)
		{
			printf("Failed to accept client connection \n");
		}
		fprintf(stdout, "Client connected: socket fd %d , %s \n", client_sock, inet_ntoa(addr_client.sin_addr));
		/*Handle this connect */
		if (fd_count<1024)
		{
			sock_clients[fd_count] = client_sock;
			if (CreateThread(NULL, 0, handle_client, &sock_clients[fd_count], 0, NULL) == NULL)
				return -1;
			++fd_count;
		}

		Sleep(10);
	}

	closesocket(listener);
	return 0;
}

int main(int c, char **v)
{

#ifdef WIN32
	init_win_socket();
#endif

	run();

	getchar();
	return 0;
}